﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace S.Breeding.Infrastructure
{
    public class BaseRepository<T> :IRepository<T> where T : class , new()
    {
        private readonly EFDbContext db;
        public BaseRepository(EFDbContext db)
        {
            this.db = db;
        }

        public async Task<IQueryable<T>> AllAsync()
        {
            return await Task.FromResult(db.Set<T>().AsQueryable());
        }

        public async Task<int> CreateAsync(T entity)
        {
            db.AddAsync(entity);
            return await db.SaveChangesAsync();

        }

        public async Task<int> DeleteAllAsync(Expression<Func<T, bool>> expression)
        {
            DbSet<T> dbset = db.Set<T>();
            var res = dbset.Where(expression);
            dbset.RemoveRange(res);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(int Id)
        {
            DbSet<T> dbset = db.Set<T>();
            var result = dbset.Find(Id);
            db.Remove(result);
            return await db.SaveChangesAsync();
        }

        public async Task<T> GetAsync(int id)
        {
            DbSet<T> dbset = db.Set<T>();
            return await dbset.FindAsync(id);
        }

        public async Task<List<T>> GetValues(Expression<Func<T, bool>> expression)
        {
            DbSet<T> dbset = db.Set<T>();
            var list = await dbset.Where(expression).ToListAsync();
            return list;
        }

        public async Task<IQueryable<T>> All()
        {
            return await Task.FromResult(db.Set<T>().AsQueryable());
        }

        public async Task<int> UpdateAsync(T entity)
        {
            db.UpdateRange(entity);
            return await db.SaveChangesAsync();
        }

        public T Get(int id)
        {
            return db.Set<T>().Find(id);
        }
    }
}
